﻿using System.Xml;
using UIShell.OSGi;
using Pasys.PresentationCore;
using Pasys.PresentationCore.Utility;

namespace Pasys.Document
{
    internal class SettingViewProviderBuilder : BuilderBase<ISettingViewProvider>
    {
        private const string ATTR_TYPE = "type";
        public override void Build(XmlNode xmlNode, IBundle owner)
        {

            var parentSettingKey=XmlUtility.ReadAttribute(xmlNode, "parentSettingKey");
            var settingKey = XmlUtility.ReadAttribute(xmlNode, "settingKey");
            var title = XmlUtility.ReadAttribute(xmlNode, "title");

            if (xmlNode.Name == "SettingPath")
            {
                if (string.IsNullOrEmpty(settingKey))
                {
                    return;
                }
                if (string.IsNullOrEmpty(title))
                {
                    title = settingKey;
                }

                SettingViewPathBaseProvider path = new SettingViewPathBaseProvider(settingKey);
                path.SetParentSettingKey(parentSettingKey); //XmlUtility.ReadAttribute(xmlNode, "ParentSettingKey"));
                path.SetTitle(title);//XmlUtility.ReadAttribute(xmlNode, "Title"));
                AddItem(path);
            }
            else
            {
                string providerName = XmlUtility.ReadAttribute(xmlNode, ATTR_TYPE);
                if (string.IsNullOrEmpty(providerName))
                { return; }
                var result = System.Activator.CreateInstance(owner.LoadClass(providerName)) as ISettingViewProvider;
                if (result != null)
                {
                    if (!string.IsNullOrEmpty(title))
                    {
                        result.SetTitle(title);
                    }
                    if (!string.IsNullOrEmpty(parentSettingKey))
                    {
                        result.SetParentSettingKey(parentSettingKey);
                    }

                    AddItem(result);
                }
            }
        }
    }
}
